package com.tg.app.helper;

import static com.tg.app.activity.device.DeviceSettingsActivity.EXT_DEVICE_INFO;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.appbase.custom.constant.CommonConstants;
import com.tange.base.toolkit.StringUtils;
import com.tange.core.backend.service.ep.EnvironmentProxy;
import com.tange.core.initialization.TGCore;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.device.feature.DeviceFeature;
import com.tange.module.device.feature.DeviceFeatureObjectBox;
import com.tange.module.device.feature.DeviceFeature_;
import com.tencent.bugly.crashreport.CrashReport;
import com.tg.app.BuildConfig;
import com.tg.app.R;
import com.tg.app.TGSdk;
import com.tg.app.TGSdkHelper;
import com.tg.app.activity.CloudServiceActivity;
import com.tg.app.activity.base.DeviceListBaseActivity;
import com.tg.app.activity.base.WebBaseActivity;
import com.tg.app.activity.device.CameraViewActivity;
import com.tg.app.activity.device.DeviceListActivity;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.app.activity.device.add.SelectDeviceActivity;
import com.tg.app.activity.tools.DevToolsActivity;
import com.tg.app.camera.Camera;
import com.tg.app.push.TangeMessageReceiver;
import com.tg.app.util.LogUtils;
import com.tg.app.util.ObjectBoxUtil;
import com.tg.app.util.UriUtil;
import com.tg.appcommon.android.AbAppUtil;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.business.IAppModule;
import com.tg.appcommon.business.ILoginModule;
import com.tg.appcommon.business.IMessageModule;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.helper.DeviceItemHelper;
import com.tg.data.helper.DeviceTypeHelper;
import com.tg.data.http.entity.MessageDataBean;
import com.tg.data.http.entity.PushEventBean;
import com.tg.message.msg.MessageDataHolder;
import com.tg.message.msg.MessagePlayActivity;
import com.umeng.commonsdk.UMConfigure;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.objectbox.Box;

public class ModuleImpl implements IAppModule, ILoginModule, IMessageModule {
    private static final String TAG = "AppModuleImpl";

    public static final String IS_SHARE_ITEM = "is_share_item";
    public static final ModuleImpl sImpl = new ModuleImpl();


    @Override
    public void openServePlay(Activity activity, String url, long deviceId, int type, int requestCode) {
        UriUtil.openServePlay(activity, url, deviceId, type, requestCode);
    }

    @Override
    public void launchSuperAI(Context context, Object item) {
        if(!(item instanceof DeviceItem)) {
            return;
        }

        DeviceItem deviceItem = (DeviceItem) item;
        if (!StringUtils.isEmpty(deviceItem.foreignServiceHook)){
            AbAppUtil.openServeByBrowser(context, deviceItem.foreignServiceHook);
        }else{
            Intent intent = new Intent();
            DeviceSettingsInfo info = new DeviceSettingsInfo();
            info.deviceID = deviceItem.id;
            info.uuid = deviceItem.uuid;
            intent.putExtra(EXT_DEVICE_INFO, info);
            intent.putExtra(CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE, CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE_SUPER_AI);
            intent.setClass(context, CloudServiceActivity.class);
            context.startActivity(intent);
        }
    }

    @Override
    public void launchSuperAIPay(Context context, Object item) {
        if(!(item instanceof DeviceItem)) {
            return;
        }

        DeviceItem deviceItem = (DeviceItem) item;

        if (!StringUtils.isEmpty(deviceItem.foreignServiceHook)){
            AbAppUtil.openServeByBrowser(context, deviceItem.foreignServiceHook);
        } else if (TGGlobalConfigHelper.getInstance().config() != null && !TextUtils.isEmpty(TGGlobalConfigHelper.getInstance().config().super_ai_service_buy)) {
            openWebService(context, deviceItem, TGGlobalConfigHelper.getInstance().config().super_ai_service_buy);
        } else {
            launchSuperAI(context, item);
        }
    }


    @Override
    public void launchAIorSuperAIPay(Context context, Object item) {
        if(!(item instanceof DeviceItem)) {
            return;
        }

        DeviceItem deviceItem = (DeviceItem) item;

        if (!StringUtils.isEmpty(deviceItem.foreignServiceHook)){
            AbAppUtil.openServeByBrowser(context, deviceItem.foreignServiceHook);
        }else if (DeviceHelper.isBirdFeeder(deviceItem)){
            openWebService(context, deviceItem, CloudServiceActivity.EXT_BIRD_FEEDER_SERVICE_TYPE_STORAGEORCAR);
        }else if (DeviceItemHelper.isSuperAiService(deviceItem)){
            if (TGGlobalConfigHelper.getInstance().config() != null && !TextUtils.isEmpty(TGGlobalConfigHelper.getInstance().config().super_ai_service_buy)) {
                openWebService(context, deviceItem, TGGlobalConfigHelper.getInstance().config().super_ai_service_buy);
            } else {
                openWebService(context, deviceItem, CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE_SUPER_AI);
            }
        }else{
            if (TGGlobalConfigHelper.getInstance().config() != null && !TextUtils.isEmpty(TGGlobalConfigHelper.getInstance().config().ai_service_buy)) {
                openWebService(context, deviceItem, TGGlobalConfigHelper.getInstance().config().ai_service_buy);
            } else {
                openWebService(context, deviceItem, CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE_AI);
            }
        }
    }

    @Override
    public void launchCloudServicePay(Context context, Object deviceItem) {
        if (deviceItem instanceof DeviceItem) {
            final DeviceItem item = (DeviceItem) deviceItem;

            if (!StringUtils.isEmpty(item.foreignServiceHook)){
                AbAppUtil.openServeByBrowser(context, item.foreignServiceHook);
                return;
            }

            if (DeviceHelper.isBirdFeeder(item)){
                launchAIorSuperAIPay(context, deviceItem);
                return;
            }
            if (DeviceHelper.isDoorBell(item)){
                openWebService(context, (DeviceItem) deviceItem, CloudServiceActivity.EXT_DOORBELL_SERVICE_TYPE_STORAGEORCAR);
                return;
            }


            if (DeviceHelper.isLockBell(item)){
                openWebService(context, (DeviceItem) deviceItem, CloudServiceActivity.EXT_LOCKBELL_SERVICE_TYPE_STORAGEORCAR);
                return;
            }

            String url;
            if (TGGlobalConfigHelper.getInstance().config() != null && !TextUtils.isEmpty(TGGlobalConfigHelper.getInstance().config().storage_service_buy)) {
                if (item.isCar()) {
                    url = TGGlobalConfigHelper.getInstance().config().car_service_buy;
                } else if (item.is4GDevice()) {
                    url = TGGlobalConfigHelper.getInstance().config().sim_service_buy;
                } else {
                    url = TGGlobalConfigHelper.getInstance().config().storage_service_buy;
                }
                if (!TextUtils.isEmpty(url)) {
                    openWebService(context, (DeviceItem) deviceItem, url);
                } else {
                    openWebService(context, (DeviceItem) deviceItem, CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE_STORAGEORCAR);
                }
            } else {
                openWebService(context, (DeviceItem) deviceItem, CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE_STORAGEORCAR);
            }
        }
    }


    private void openWebService(Context context, DeviceItem deviceItem, int type) {
        if (deviceItem != null && !StringUtils.isEmpty(deviceItem.foreignServiceHook)){
            AbAppUtil.openServeByBrowser(context, deviceItem.foreignServiceHook);
        }else{
            Intent intent = new Intent();
            DeviceSettingsInfo info = new DeviceSettingsInfo();
            info.deviceID = deviceItem.id;
            info.uuid = deviceItem.uuid;
            intent.putExtra(EXT_DEVICE_INFO, info);
            intent.putExtra(CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE, type);
            intent.setClass(context, CloudServiceActivity.class);
            context.startActivity(intent);
        }

    }

    private void openWebService(Context context, DeviceItem deviceItem, String url) {
        TGLog.i(TAG, "[openWebService] url = " + url);
        TGToast.showToast("该功能暂未开放");
        if (deviceItem != null && !StringUtils.isEmpty(deviceItem.foreignServiceHook)){
            AbAppUtil.openServeByBrowser(context, deviceItem.foreignServiceHook);
        }else{
            Intent intent = new Intent();
            DeviceSettingsInfo info = new DeviceSettingsInfo();
            info.deviceID = deviceItem.id;
            info.uuid = deviceItem.uuid;
            intent.putExtra(EXT_DEVICE_INFO, info);
            intent.putExtra(CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE, 0);
            intent.putExtra(WebBaseActivity.KEY_WEBURL, url);
            intent.setClass(context, CloudServiceActivity.class);
            context.startActivity(intent);

        }

    }

    @Override
    public void onClickServeBtn(Activity activity, boolean canLive, Object deviceItem, Object message) {
        if (canLive) {
            DeviceHelper.openDevice(activity, (DeviceItem) deviceItem, DeviceListBaseActivity.PUSH_TARGET_LIVE);
            return;
        }
        DeviceItem item = (DeviceItem) deviceItem;
        MessageDataBean.ItemsBean eventMessage = (MessageDataBean.ItemsBean)message;
        if (DeviceTypeHelper.isCar(item.device_type)) { //行车记录仪
            ActivityHelper.startCameraActivityFromMessage(activity, eventMessage, item, DeviceItemHelper.isStandard(item) && eventMessage.getIs_pay() == 1);
        } else {
            boolean is4gCloud = !DeviceItemHelper.is4GDevice(item) || DeviceItemHelper.is4GHasCloud(item);
            boolean isCloud = is4gCloud && eventMessage.getIs_pay() == 1 && DeviceItemHelper.hasServe(item);
            if (DeviceHelper.isLamp((DeviceItem) deviceItem)){
                isCloud = true;
            }
            ActivityHelper.startCameraActivityFromMessage(activity, eventMessage, item, isCloud);
        }
    }

    @Override
    public boolean isNoMedia(Object object) {
        if (object instanceof DeviceItem){
            return DeviceHelper.isNoMedia((DeviceItem)object);
        }
        return false;
    }

    @Override
    public boolean isBatteryDevice(Object deviceItem) {
        if (deviceItem instanceof DeviceItem) {
            return DeviceHelper.isBatteryDevice((DeviceItem) deviceItem);
        } else {
            return false;
        }
    }

    @Override
    public boolean isLockBell(Object deviceItem) {
        if (deviceItem instanceof DeviceItem) {
            return DeviceHelper.isLockBell((DeviceItem) deviceItem);
        } else {
            return false;
        }
    }

    @Override
    public boolean isLamp(Object deviceItem) {
        if (deviceItem instanceof DeviceItem) {
            return DeviceHelper.isLamp((DeviceItem) deviceItem);
        } else {
            return false;
        }
    }


    @Override
    public void goToDeviceListPage(Context context, Bundle extras) {
        ActivityHelper.gotoDeviceListPage(context, extras);
    }

    @Override
    public void goToDeviceListPage(Context context) {
        ActivityHelper.gotoDeviceListPage(context);
    }

    @Override
    public void getAgreementForWebView(Context context, int flag) {
        ActivityHelper.getAgreementForWebView(context, flag);
    }

    @Override
    public void agreeProtocol(Context context) {
     //   SpeechHelper.createUtility(context, BuildConfig.APP_ID_SPEECH);
        CrashReport.initCrashReport(context.getApplicationContext());
        UMConfigure.init(context, null,null, UMConfigure.DEVICE_TYPE_PHONE, null);

        TGCore.INSTANCE.initializeOnUserProtocolAgreed(TGApplicationBase.getApplication());
    }

    @Override
    public void startDevToolsActivity(Context context) {
        Intent intent = new Intent(context, DevToolsActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void register(Context context) {
        ActivityHelper.startRegisterActivity(context);
    }

    @Override
    public void startLoginActivity(Context context, String from) {
        ActivityHelper.startLoginActivity(context, from);
    }

    @Override
    public void removeAllCamera() {
        CameraHub.getInstance().removeAll();
    }

    @Override
    public boolean isThirdPartyApp() {
        return TGSdk.getInstance().isThirdPartyApp();
    }

    @Override
    public void notifyMessage(int messageId, String message){
        TGSdk.getInstance().notifyMessage(messageId, message);
    }
    @Override
    public void onEventClickByName(String name, String btn) {
        LogUtils.onEventClickByName(name, btn);
    }

    @Override
    public void onMessageItemClick(Activity activity, Object itemsBean, Object deviceItem, String desKey) {
        Intent intent = new Intent();
        DeviceItem item  = null;
        if (deviceItem instanceof DeviceItem){
            item = (DeviceItem)deviceItem;
        }
        MessageDataBean.ItemsBean message = null;
        if (itemsBean instanceof MessageDataBean.ItemsBean){
            message = (MessageDataBean.ItemsBean)itemsBean;
        }

        if (item != null && message != null){
            message.setCategory(item.getCategory());
        }
        if (message==null)return;
        intent.putExtra(EXT_EVENT_MESSAGE, message);

        intent.setClass(activity, MessagePlayActivity.class);
        intent.putExtra(IS_SHARE_ITEM, item != null && item.isShare());
        intent.putExtra(EXT_DEVICE_DES, desKey);
        intent.putExtra(MessageDataHolder.EXT_DEVICE, item);
        activity.startActivityForResult(intent, 2);
    }

    @Override
    public Object getMessageFilter() {
        return ObjectBoxUtil.getMessageFilter();
    }

    @Override
    public Object getDeviceSettingsInfo(){
        return ObjectBoxUtil.getDeviceSettingsInfo();
    }

    @Override
    public List<Integer> getEventArrs(String uuid) {
        Box<DeviceFeature> featureBox = DeviceFeatureObjectBox.getDeviceFeature();
        List<Integer> list = new ArrayList<>();
        if (featureBox != null){
            DeviceFeature deviceFeature = featureBox.query().equal(DeviceFeature_.uuid, uuid).build().findFirst();
            if (deviceFeature != null){
                if (deviceFeature.supportHumidity || deviceFeature.supportTemper){
                    if (deviceFeature.supportHumidity && deviceFeature.supportTemper){
                        list.addAll(Arrays.asList(19, 20, 21, 22));
                    }else if (deviceFeature.supportTemper){
                        list.addAll(Arrays.asList(19, 20));
                    }else{
                        list.addAll(Arrays.asList(21, 22));
                    }
                }
            }
        }

        return list;
    }
}
